#!/usr/bin/env python

import urllib2
import binascii
import re
import sys

re_loc = '<td align="center"><ul class="ul1"><li>(.*?)</li><li>'

def locate(ip):

	url = 'http://ip138.com/ips1388.asp?ip=%s&action=2' % ip

	headers = {
'Accept': '*/*',
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
'Pragma': 'no-cache',
#'Cookie': 'pgv_pvi=484727808; pgv_si=s7039564800; ASPSESSIONIDSCTQQRTR=DMBKGDLCAHJMNAFIGBMPFLPF',
}

	httpHandler = urllib2.HTTPHandler(debuglevel=0)
	httpsHandler = urllib2.HTTPSHandler(debuglevel=0)

	opener = urllib2.build_opener(httpHandler, httpsHandler)
	#opener.addheaders = headers
	#f = opener.open(url, data)

	urllib2.install_opener(opener)

	req = urllib2.Request(url)
	for k, v in headers.iteritems():
		req.add_header(k, v)

	f = urllib2.urlopen(req)

	resp = f.read()

	info = re.findall(re_loc, resp)
	location = info[0].decode('gbk')[6:]
	location = location.encode('utf8')

	print '%s: %s' % (ip, location)

if len(sys.argv) <=1:
	print "Usage: %s ip ..." % sys.argv[0]
	sys.exit(0)

for ip in sys.argv[1:]:
	locate(ip)



